<?php


namespace common\behaviors;


use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;

class ModelCacheBehavior extends Behavior
{
    /**
     * Declares event handlers for the [[owner]]'s events.
     * @return array events (array keys) and the corresponding event handler methods (array values).
     */
    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_INSERT => 'handler',
            ActiveRecord::EVENT_AFTER_UPDATE => 'handler',
            ActiveRecord::EVENT_AFTER_DELETE => 'handler',
        ];
    }

    /**
     * @param Event $event
     */
    public function handler($event)
    {
        $cache = \Yii::$app->cache;
        if ($cache) {
            $key = $this->owner::getAutoCacheDependencyKey();
            $cache->set($key, time(), 600);
        }
    }
}